package com.cskaoyan.app.config;

import com.cskaoyan.app.shiro.CustomRealm;
import com.cskaoyan.app.shiro.CustomShiroSessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {
    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm realm,
         CustomShiroSessionManager sessionManager) {
        // 使用securityManager将前面注册的realm工具和sessionManager工具管理起来
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 去除重定向的Jsessionid
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        // 设置默认超时为1小时
        sessionManager.setGlobalSessionTimeout(3600000);
        securityManager.setSessionManager(sessionManager);
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/admin/auth/fail");
        shiroFilterFactoryBean.setUnauthorizedUrl("/admin/auth/fail");

        LinkedHashMap<String, String> chainMap = new LinkedHashMap<>();

        // 匿名可访问登录接口
        chainMap.put("/admin/auth/**", "anon");
        chainMap.put("/wx/auth/**", "anon");
        chainMap.put("/wx/home/**", "anon");
        chainMap.put("/wx/catalog/**", "anon");
        chainMap.put("/wx/goods/**", "anon");
        chainMap.put("/wx/brand/**", "anon");
        chainMap.put("/wx/search/**", "anon");
        chainMap.put("/wx/topic/**", "anon");
        chainMap.put("/wx/comment/list", "anon");
        chainMap.put("/wx/comment/count", "anon");
        chainMap.put("/wx/coupon/**", "anon");
        chainMap.put("/wx/issue/**", "anon");
        chainMap.put("/wx/goods/count", "anon");
        chainMap.put("/wx/storage/upload", "anon");
        // admin其他接口一律需要登录认证
        chainMap.put("/admin/**", "authc");
        chainMap.put("/wx/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(chainMap);
        return shiroFilterFactoryBean;
    }
}
